$(document).ready(function () {
    $('.ch_avatar, #avatar').click(function () {
        var fancyHref = './usuario/chosepic';
        var atualSrc = $('#avatar').attr('src');
        $.fancybox({
            type: 'ajax',
            href: fancyHref,
            maxWidth: '300px',
            openEffect: 'elastic',
            closeEffect: 'elastic',
            ajax: {
                complete: function (jqXHR, textStatus) {
                    $('.image-editor').cropit({
                        imageState: {
                            src: atualSrc
                        }
                    });
                    $('#choose').click(function (e) {
                        e.preventDefault();
                        $('#chooseinput').trigger('click');
                        return false;
                    });
                    $('#salvar').click(function () {
                        var imageData = $('.image-editor').cropit('export');
                        var imageName = $('#avatar').attr('src');
                        $.post('usuario/uploadpic', {'data': imageData, 'name': imageName})
                                .done(function (data) {
                                    $('#avatar, .nav-user-photo').attr('src', imageData);
                                });
                        $.fancybox.close();
                    });
                }
            }
        });
    });

    $('#hoverbox').mouseleave(function () {
        $('#hoverbox').hide(200);
    });

    $(".colegas img").mouseenter(function (e) {
        var uCard = $(this);
        var lft = ($(window).width() > 400) ? uCard.closest('li').offset().left + 30 : 1;
        var colegaId = uCard.attr('data-user');
        var pos = {
            top: uCard.closest('li').offset().top + 73,
            left: lft
        };
        $('#hoverbox').css(pos).stop().show(400).html('Carregando...').load('./usuario/colegadetail?id=' + colegaId);
    }).closest('li').mouseleave(function (e) {
        if ($(e.relatedTarget).attr('id') !== "hoverbox" && $(e.relatedTarget).closest('#hoverbox').length === 0) {
            $('#hoverbox').hide(200);
        }
        ;
    });
});